import React, { useRef, useState, useEffect } from 'react';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  getList,
  setStatus,
  del,
  setSorts,
  delAll,
} from '@/services/writingAdmin/setting/work/api';
import { getStorage } from '@/services/writingAdmin/setting/config/api';
import { Switch, Space, message } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import { exportExcel } from '@/utils/ExportExcel';
import { getSort, setLsetData } from '@/utils/utils';
import FormIndex from './components/FormIndex';
import NumberInput from '@/components/common/NumberInput';
import CDel from '@/components/common/CDel';
import CDelAll from '@/components/common/CDelAll';
const Index: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [storageData, setStorageData] = useState<any>(null);
  let maps = {};
  const fetchApi = async () => {
    const res = await getStorage();
    if (res.status == 20000) {
      const dynastyData = [];
      if (res.data.dynasty_list) {
        for (let i = 0; i < res.data.dynasty_list.length; i++) {
          dynastyData[res.data.dynasty_list[i].id] = {
            text: res.data.dynasty_list[i].name,
            status: res.data.dynasty_list[i].id,
          };
        }
      }
      res.data.dynasty_list = dynastyData;
      const authorData = [];
      if (res.data.author_list) {
        for (let i = 0; i < res.data.author_list.length; i++) {
          authorData[res.data.author_list[i].id] = {
            text: res.data.author_list[i].name,
            status: res.data.author_list[i].id,
          };
        }
      }
      res.data.author_list = authorData;

      const allusionData = [];
      if (res.data.allusion_list) {
        for (let i = 0; i < res.data.allusion_list.length; i++) {
          allusionData[res.data.allusion_list[i].id] = {
            text: res.data.allusion_list[i].name,
            status: res.data.allusion_list[i].id,
          };
        }
      }
      res.data.allusion_list = allusionData;

      const anthologyData = [];
      if (res.data.anthology_list) {
        for (let i = 0; i < res.data.anthology_list.length; i++) {
          anthologyData[res.data.anthology_list[i].id] = {
            text: res.data.anthology_list[i].name,
            status: res.data.anthology_list[i].id,
          };
        }
      }
      res.data.anthology_list = anthologyData;

      const themeData = [];
      if (res.data.theme_list) {
        for (let i = 0; i < res.data.theme_list.length; i++) {
          themeData[res.data.theme_list[i].id] = {
            text: res.data.theme_list[i].name,
            status: res.data.theme_list[i].id,
          };
        }
      }
      res.data.theme_list = themeData;

      const brandData = [];
      if (res.data.brand_list) {
        for (let i = 0; i < res.data.brand_list.length; i++) {
          brandData[res.data.brand_list[i].id] = {
            text: res.data.brand_list[i].name,
            status: res.data.brand_list[i].id,
          };
        }
      }
      res.data.brand_list = brandData;

      const geographyData = [];
      if (res.data.geography_list) {
        for (let i = 0; i < res.data.geography_list.length; i++) {
          geographyData[res.data.geography_list[i].id] = {
            text: res.data.geography_list[i].name,
            status: res.data.geography_list[i].id,
          };
        }
      }
      res.data.geography_list = geographyData;

      const famousMountainData = [];
      if (res.data.famous_mountain_list) {
        for (let i = 0; i < res.data.famous_mountain_list.length; i++) {
          famousMountainData[res.data.famous_mountain_list[i].id] = {
            text: res.data.famous_mountain_list[i].name,
            status: res.data.famous_mountain_list[i].id,
          };
        }
      }
      res.data.famous_mountain_list = famousMountainData;

      const cityData = [];
      if (res.data.citys_mountain_list) {
        for (let i = 0; i < res.data.citys_mountain_list.length; i++) {
          cityData[res.data.citys_mountain_list[i].id] = {
            text: res.data.citys_mountain_list[i].name,
            status: res.data.citys_mountain_list[i].id,
          };
        }
      }
      res.data.citys_mountain_list = cityData;

      const timeMData = [];
      if (res.data.time_ms_mountain_list) {
        for (let i = 0; i < res.data.time_ms_mountain_list.length; i++) {
          timeMData[res.data.time_ms_mountain_list[i].id] = {
            text: res.data.time_ms_mountain_list[i].name,
            status: res.data.time_ms_mountain_list[i].id,
          };
        }
      }
      res.data.time_ms_mountain_list = timeMData;

      const describeScenerysMountainData = [];
      if (res.data.describe_scenerys_mountain_list) {
        for (let i = 0; i < res.data.describe_scenerys_mountain_list.length; i++) {
          describeScenerysMountainData[res.data.describe_scenerys_mountain_list[i].id] = {
            text: res.data.describe_scenerys_mountain_list[i].name,
            status: res.data.describe_scenerys_mountain_list[i].id,
          };
        }
      }
      res.data.describe_scenerys_mountain_list = describeScenerysMountainData;

      const festivalData = [];
      if (res.data.festivals_mountain_list) {
        for (let i = 0; i < res.data.festivals_mountain_list.length; i++) {
          festivalData[res.data.festivals_mountain_list[i].id] = {
            text: res.data.festivals_mountain_list[i].name,
            status: res.data.festivals_mountain_list[i].id,
          };
        }
      }
      res.data.festivals_mountain_list = festivalData;

      const solarTermData = [];
      if (res.data.solar_term_list) {
        for (let i = 0; i < res.data.solar_term_list.length; i++) {
          solarTermData[res.data.solar_term_list[i].id] = {
            text: res.data.solar_term_list[i].name,
            status: res.data.solar_term_list[i].id,
          };
        }
      }
      res.data.solar_term_list = solarTermData;

      const seasonData = [];
      if (res.data.season_list) {
        for (let i = 0; i < res.data.season_list.length; i++) {
          seasonData[res.data.season_list[i].id] = {
            text: res.data.season_list[i].name,
            status: res.data.season_list[i].id,
          };
        }
      }
      res.data.season_list = seasonData;

      const flowersPlantData = [];
      if (res.data.flowers_plant_list) {
        for (let i = 0; i < res.data.flowers_plant_list.length; i++) {
          flowersPlantData[res.data.flowers_plant_list[i].id] = {
            text: res.data.flowers_plant_list[i].name,
            status: res.data.flowers_plant_list[i].id,
          };
        }
      }
      res.data.flowers_plant_list = flowersPlantData;

      const textbookData = [];
      if (res.data.textbook_list) {
        for (let i = 0; i < res.data.textbook_list.length; i++) {
          textbookData[res.data.textbook_list[i].id] = {
            text: res.data.textbook_list[i].name,
            status: res.data.textbook_list[i].id,
          };
        }
      }
      res.data.textbook_list = textbookData;

      await setStorageData(res.data);
    }
  };
  useEffect(() => {
    fetchApi();
  }, []);
  const columns: ProColumns<API.WritingAdminWorkList>[] = [
    {
      title: '编号',
      dataIndex: 'id',
      hideInSearch: true,
      align: 'center',
      width: 80,
      fixed: true,
    },
    {
      title: '名称',
      dataIndex: 'title',
      align: 'center',
      width: 200,
    },
    {
      title: '作者',
      dataIndex: 'author',
      hideInSearch: true,
      width: 150,
      align: 'center',
    },
    {
      title: '作者',
      dataIndex: 'author_id',
      valueType: 'select',
      fieldProps: {
        showSearch: true,
      },
      valueEnum: storageData ? storageData.author_list : [],
      hideInTable: true,
    },
    {
      title: '朝代',
      dataIndex: 'dynasty',
      hideInSearch: true,
      width: 150,
      align: 'center',
    },
    {
      title: '朝代',
      dataIndex: 'dynasty_id',
      valueType: 'select',
      fieldProps: {
        showSearch: true,
      },
      valueEnum: storageData ? storageData.dynasty_list : [],
      hideInTable: true,
    },
    {
      title: '用典',
      dataIndex: 'allusion_id',
      valueType: 'select',
      fieldProps: {
        showSearch: true,
      },
      valueEnum: storageData ? storageData.allusion_list : [],
      hideInTable: true,
    },
    {
      title: '选集',
      dataIndex: 'anthology_id',
      valueType: 'select',
      fieldProps: {
        showSearch: true,
      },
      valueEnum: storageData ? storageData.anthology_list : [],
      hideInTable: true,
    },
    {
      title: '主题',
      dataIndex: 'theme_id',
      valueType: 'select',
      fieldProps: {
        showSearch: true,
      },
      valueEnum: storageData ? storageData.theme_list : [],
      hideInTable: true,
    },
    {
      title: '词牌',
      dataIndex: 'brand_id',
      valueType: 'select',
      fieldProps: {
        showSearch: true,
      },
      valueEnum: storageData ? storageData.brand_list : [],
      hideInTable: true,
    },
    {
      title: '地理',
      dataIndex: 'geography_id',
      valueType: 'select',
      fieldProps: {
        showSearch: true,
      },
      valueEnum: storageData ? storageData.geography_list : [],
      hideInTable: true,
    },
    {
      title: '名山',
      dataIndex: 'famous_mountain_id',
      valueType: 'select',
      fieldProps: {
        showSearch: true,
      },
      valueEnum: storageData ? storageData.famous_mountain_list : [],
      hideInTable: true,
    },
    {
      title: '城市',
      dataIndex: 'city_id',
      valueType: 'select',
      fieldProps: {
        showSearch: true,
      },
      valueEnum: storageData ? storageData.citys_mountain_list : [],
      hideInTable: true,
    },
    {
      title: '时间',
      dataIndex: 'time_m_id',
      valueType: 'select',
      fieldProps: {
        showSearch: true,
      },
      valueEnum: storageData ? storageData.time_ms_mountain_list : [],
      hideInTable: true,
    },
    {
      title: '写景',
      dataIndex: 'describe_scenery_id',
      valueType: 'select',
      fieldProps: {
        showSearch: true,
      },
      valueEnum: storageData ? storageData.describe_scenerys_mountain_list : [],
      hideInTable: true,
    },
    {
      title: '节日',
      dataIndex: 'festival_id',
      valueType: 'select',
      fieldProps: {
        showSearch: true,
      },
      valueEnum: storageData ? storageData.festivals_mountain_list : [],
      hideInTable: true,
    },
    {
      title: '节气',
      dataIndex: 'solar_term_id',
      valueType: 'select',
      fieldProps: {
        showSearch: true,
      },
      valueEnum: storageData ? storageData.solar_term_list : [],
      hideInTable: true,
    },
    {
      title: '时令',
      dataIndex: 'season_id',
      valueType: 'select',
      fieldProps: {
        showSearch: true,
      },
      valueEnum: storageData ? storageData.season_list : [],
      hideInTable: true,
    },
    {
      title: '花卉',
      dataIndex: 'flowers_plant_id',
      valueType: 'select',
      fieldProps: {
        showSearch: true,
      },
      valueEnum: storageData ? storageData.flowers_plant_list : [],
      hideInTable: true,
    },
    {
      title: '课本',
      dataIndex: 'textbook_id',
      valueType: 'select',
      fieldProps: {
        showSearch: true,
      },
      valueEnum: storageData ? storageData.textbook_list : [],
      hideInTable: true,
    },
    {
      title: '抓取地址',
      dataIndex: 'baidu_wiki',
      hideInSearch: true,
      align: 'center',
      width: 200,
      ellipsis: true,
      render: (text, record) => (
        <a href={'' + record.baidu_wiki} target="_blank">
          {text}
        </a>
      ),
    },
    {
      title: '排序',
      dataIndex: 'sort',
      hideInSearch: true,
      sorter: true,
      width: 80,
      align: 'center',
      render: (text, record) => [
        <NumberInput
          key={record.id}
          value={record.sort}
          onBlur={async (value: number) => {
            const res = await setSorts(record.id, { sort: value });
            if (res.status === 20000) {
              message.success(res.message);
            } else {
              actionRef.current?.reload();
            }
          }}
        />,
      ],
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueType: 'select',
      valueEnum: {
        0: {
          text: '禁用',
          status: '0',
        },
        1: {
          text: '启用',
          status: '1',
        },
      },
      hideInTable: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
      width: 100,
      align: 'center',
      render: (text, record) => [
        <Switch
          key={record.id + record.status}
          checkedChildren="启用"
          unCheckedChildren="禁用"
          defaultChecked={record.status === 1 ? true : false}
          onChange={async (checked: boolean) => {
            const res = await setStatus(record.id, { status: checked ? 1 : 0 });
            if (res.status === 20000) {
              message.success(res.message);
            } else {
              actionRef.current?.reload();
            }
          }}
        />,
      ],
    },

    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      valueType: 'dateTime',
      sorter: true,
      hideInSearch: true,
      width: 180,
      align: 'center',
    },
    {
      title: '创建时间',
      key: 'created_at',
      dataIndex: 'created_at',
      valueType: 'dateTimeRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            'created_at[0]': value[0],
            'created_at[1]': value[1],
          };
        },
      },
    },
    {
      title: '更新时间',
      key: 'updated_at',
      dataIndex: 'updated_at',
      valueType: 'dateTime',
      sorter: true,
      hideInSearch: true,
      width: 180,
      align: 'center',
    },
    {
      title: '更新时间',
      key: 'updated_at',
      dataIndex: 'updated_at',
      valueType: 'dateTimeRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            updated_at: value,
          };
        },
      },
    },
    {
      title: '操作',
      key: 'option',
      width: 150,
      valueType: 'option',
      align: 'center',
      fixed: 'right',
      render: (_, row) => [
        <FormIndex
          id={row.id}
          key={row.id}
          onConfirm={() => {
            return actionRef.current?.reload();
          }}
        />,
        <CDel
          key={row.id}
          onCancel={async () => {
            const res = await del(row.id);
            if (res.status === 20000) {
              message.success(res.message);
              actionRef.current?.reload();
            }
          }}
        />,
      ],
    },
  ];
  return (
    <PageContainer fixedHeader={true} title={false}>
      <ProTable
        scroll={{ x: 1300 }}
        actionRef={actionRef}
        rowKey="id"
        columns={columns}
        request={async (params: API.ListQequest, sort) => {
          const data: any = await getSort(params, sort);
          const res = await getList(data);
          return setLsetData(res);
        }}
        options={{ fullScreen: true }}
        rowSelection={{ fixed: true }}
        tableAlertRender={({ selectedRowKeys, onCleanSelected }) => (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 项
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消选择
              </a>
            </span>
          </Space>
        )}
        columnsState={{
          onChange: (map) => {
            maps = map;
          },
        }}
        tableAlertOptionRender={({ selectedRows, selectedRowKeys, onCleanSelected }) => {
          return (
            <Space size={16}>
              <CDelAll
                key={selectedRowKeys.length}
                count={selectedRowKeys.length}
                onCancel={async () => {
                  const res = await delAll({ idArr: selectedRowKeys });
                  if (res.status === 20000) {
                    message.success(res.message);
                    actionRef.current?.reload();
                    onCleanSelected();
                  }
                }}
              />
              <a
                onClick={() => {
                  exportExcel({ fileName: '作品管理', columns, maps, selectedRows });
                }}
              >
                导出数据
              </a>
            </Space>
          );
        }}
        headerTitle={
          <FormIndex
            onConfirm={() => {
              return actionRef.current?.reload();
            }}
          />
        }
      />
    </PageContainer>
  );
};
export default Index;
